#!/usr/bin/env python3
import requests
import json
import base64
import os
import glob

def test_image(image_path, server_url="http://localhost:8080"):
    """测试单张图片的车牌识别"""
    if not os.path.exists(image_path):
        print(f"❌ 图片不存在: {image_path}")
        return False
        
    try:
        # 读取图片并编码为base64
        with open(image_path, 'rb') as f:
            image_data = f.read()
        
        b64_data = base64.b64encode(image_data).decode('utf-8')
        image_data_uri = f"data:image/jpeg;base64,{b64_data}"
        
        # 构造请求数据
        data = {
            "image_data": image_data_uri,
            "save": 1,
            "return_src": 1,
            "return_box": 1
        }
        
        print(f"\n📷 测试图片: {image_path}")
        
        response = requests.post(server_url, 
                               data=json.dumps(data),
                               headers={'Content-Type': 'application/json'},
                               timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            if result.get('errcode') == 0:
                plates = result.get('data', [])
                if plates:
                    print(f"✅ 识别成功! 找到 {len(plates)} 个车牌:")
                    for i, plate in enumerate(plates, 1):
                        print(f"   车牌{i}: {plate['plate']} ({plate['color']}) - 置信度: {plate['conf']}%")
                else:
                    print("⚠️  未识别到车牌")
                return True
            else:
                print(f"❌ 识别失败: {result.get('errinfo', '未知错误')}")
                return False
        else:
            print(f"❌ 请求失败: HTTP {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False

def main():
    server_url = "http://localhost:8080"
    
    # 获取test目录下的所有图片
    image_patterns = ["test/*.jpg", "test/*.jpeg", "test/*.png"]
    test_images = []
    for pattern in image_patterns:
        test_images.extend(glob.glob(pattern))
    
    if not test_images:
        print("❌ 在test目录下未找到图片文件")
        return
    
    # 限制测试图片数量
    test_images = sorted(test_images)[:5]  # 只测试前5张图片
    
    print("=" * 60)
    print("🚗 车牌识别服务批量测试")
    print("=" * 60)
    print(f"📊 计划测试 {len(test_images)} 张图片")
    
    success_count = 0
    total_plates = 0
    
    for image_path in test_images:
        try:
            if test_image(image_path, server_url):
                success_count += 1
        except KeyboardInterrupt:
            print("\n⏹️  测试被用户中断")
            break
        except Exception as e:
            print(f"❌ 测试图片 {image_path} 时发生错误: {e}")
    
    print("\n" + "=" * 60)
    print("📈 测试总结:")
    print(f"   总测试图片: {len(test_images)}")
    print(f"   成功识别: {success_count}")
    print(f"   成功率: {success_count/len(test_images)*100:.1f}%")
    print("=" * 60)

if __name__ == "__main__":
    main() 